﻿var readList = new Array();
var areaList = new Array();
var progList = new Array();
var areaLen = 0;
var readLen = 0;
var parentDiv = null;
var curMap = 1;
var ringDiv = null;
var oldLineStyle = null;
var oldLineElement = null;

function getId(id) {
	return "string" == typeof id ? document.getElementById(id) : id;
}

Array.prototype.contains = function(item){
	for(var i = 0; i < this.length; i ++)
	{
		if(this[i] == item)
			return true;
	}
	
	return false;
};

function _svgID2SectionNo(svgID)
{
	switch(svgID)
	{
		case "progSvg0":
			return "4";
		
		case "progSvg1":
			return "3";
				
		case "progSvg2":
			return "2";
		
		case "progSvg3":
			return "1";
		
		default:
			return "";
	}
}

function _sectionNo2SvgID(sectionNo)
{
	switch(sectionNo)
	{
		
		case "1":
			return "progSvg3";
		
		case "2":
			return "progSvg2";
		
		case "3":
			return "progSvg1";
		
		case "4":
			return "progSvg0";
		
		default:
			return "";
	}
}

function _calcEffectiveReaderID(readerMap)
{
	var l = readerMap;
	var res = new Array();
	
	for (var i = 0; i < l.length; i ++)
	{
		var elem = l[i];
		if(elem.mapID == curMap)
			res.push(elem.readerID);
	}
	
	return res;
}

function _handleHideReadersCheckBoxClick()
{
	var chk = document.getElementById("hideAllReadersChk");
	if(chk.checked)
	{
		_hideAllReader(true);
	}
	else
	{
		_hideAllReader(false);
	}
}

function _hideAllReader(hide)
{
	for (var j = 0; j < allReaderData.length; j++) {
		var l =  allReaderData[j].listRead;
		var effectiveReaders = _calcEffectiveReaderID( _getReaderMap() );
		for(var i = 0; i < l.length; i ++)
		{
			var lrmID = l[i].lrmID;
			if(!effectiveReaders.contains(lrmID))
				continue;
			
			if(hide)
			{
				getId("read"+lrmID).style.display="none";
				getId("readRadius"+lrmID).style.display="none";
			}
			else
			{
				getId("read"+lrmID).style.display="block";
				getId("readRadius"+lrmID).style.display="block";
			}
		}
	}
}

function _buildAllReader(allReaderData)
{
	//function buildRead(lrmID, lrmName, lrmType, lrmX, lrmY, lrmState, lrmTime,lrmRemark)
	for (var j = 0; j < allReaderData.length; j++) {
		var l =  allReaderData[j].listRead;
		for(var i = 0; i < l.length; i ++)
		{
			lrmID = l[i].lrmID;
			lrmType = l[i].lrmType;
			lrmX = l[i].lrmX;
			lrmY = l[i].lrmY;
			lrmState = l[i].lrmState;
			lrmTime = l[i].lrmTime;
			lrmRadius = l[i].lrmRadius;
			buildRead(lrmID, lrmID, lrmType, lrmX, lrmY, lrmState, lrmTime, lrmID, lrmRadius);
		}
	}
}

function _showCurMapReader(allReaderData, readerMap)
{
	var effectiveReaderID = _calcEffectiveReaderID(readerMap);
		for (var j = 0; j < allReaderData.length; j++) {
		var l =  allReaderData[j].listRead;
		for(var i = 0; i < l.length; i ++)
		{
			lrmID = l[i].lrmID;
			if(effectiveReaderID.contains(lrmID))
			{
				getId("read" + lrmID).style.display = "block";
				getId("readRadius" + lrmID).style.display = "block";
			}
		}
	}
}

function _removeAllReader(allReaderData)
{
	for (var j = 0; j < allReaderData.length; j++) {
		var l =  allReaderData[j].listRead;
		for(var i = 0; i < l.length; i ++)
		{
			lrmID = l[i].lrmID;
			elem = document.getElementById( "read" + lrmID );
			readRaduisElem = document.getElementById( "readRadius" + lrmID );

			if(elem)
			{
				p = elem.parentNode;
				p.removeChild(elem);
				p.removeChild(readRaduisElem);
			}
		}
	}
}


function _drawPerMapReader()
{
	resetToDefaultScale();
	var allReaderData = _getAllReaderData();
	var readerMap = _getReaderMap();
	_buildMap(curMap, curMap);
	_removeAllReader(allReaderData);
	_buildAllReader(allReaderData);
	_showCurMapReader(allReaderData, readerMap);
	_cancelReadersUpdate();
	_updateDataFlow(refreshTime);
	_fetchProgress();
	var img = new scrollImage("mapImg", 1);
	img.onload();
}

function _drawProg(x, y, w, h, svgID)
{
	var svg=document.createElementNS('http://www.w3.org/2000/svg','svg');
	svg.setAttribute("id", svgID);

	svg.style.top = y + "px";
	svg.style.left = x + "px";
	svg.style.width = w + "px";
	svg.style.height = h + "px";
	
	svg.style.position = "absolute";
	svg.style.zIndex = "9";
	svg.style.background = "#ffffff";
	svg.style.cursor = "crosshair";
	
	var g=document.createElementNS('http://www.w3.org/2000/svg','g');
	svg.appendChild(g);
	
	var parentDiv = getId("mapDiv");
	parentDiv.appendChild(svg);
	
	progList[svgID] = new Array();
	progList[svgID]["x"] = x;
	progList[svgID]["y"] = y;
	progList[svgID]["w"] = w;
	progList[svgID]["h"] = h;
}

function _progIDValid(progID)
{
	for(var key in progList)
	{
		if(typeof(progList[key]) != "object")
			continue;
		
		if(key == progID)
			return true;
	}
	
	return false;
}

function _ringMouseIn(event)
{
	if(event.srcElement.tagName != "line")
		return;
	if(!event.fromElement || event.fromElement.tagName != "svg")
		return;
	
	if(oldLineStyle && oldLineElement)
	{
		oldLineElement.setAttribute("style", oldLineStyle);
		oldLineElement = null;
		oldLineStyle = null;
	}
	
	var line = event.srcElement;
	oldLineStyle = line.getAttribute("style");
	oldLineElement = line;
	var selectedStyle = "stroke: yellow; stroke-width: 0.1;";
	line.setAttribute("style", selectedStyle);

	if(!ringDiv){
		ringDiv = document.createElement("div");
		ringDiv.style.position = "absolute";
		//ringDiv.style.width = "400px";
		//ringDiv.style.height = "400px";
		ringDiv.style.zIndex="20000";
		ringDiv.style.background="yellow";
	}

	var desc = "环号：" + line.ringNo;
	if(line.record)
		desc += "（" + "环内进度：" + line.record + "）";
	ringDiv.innerHTML = "<label>"+ desc +"</label>";
	var offsetX = parseInt( event.fromElement.style.left );
	var offsetY = parseInt( event.fromElement.style.top );
	ringDiv.style.display = "block";
	ringDiv.style.top = offsetY + event.offsetY + 5 + "px";
	ringDiv.style.left = offsetX + event.offsetX + 5 + "px";
	
	if(ringDiv.parent)
	{
		ringDiv.parent.removeChild(ringDiv);
	}
	getId("mapDiv").appendChild(ringDiv);
}

function _ringMouseOut(event)
{
	if(event.srcElement.tagName != "line")
		return;
	
	if(oldLineStyle && oldLineElement)
	{
		oldLineElement.setAttribute("style", oldLineStyle);
		oldLineElement = null;
		oldLineStyle = null;
	}
	
	if(ringDiv)
		ringDiv.style.display = "none";
}

function check_ring_no(ringNo)
{
	var pattern = /^[0-9]+$/;
	
	if(ringNo.match(pattern))
		return true;
	
	return false;
}

function show_detail_info(sectionNo, ringNo)
{
	//Change here to jump to relevant page, later;
	var HOST_ADDR = "192.168.1.120:9090";
	var svgID = _sectionNo2SvgID(sectionNo);
	ringNo = parseInt(ringNo);
	
	if(ringNo > progList[svgID]["curRingNo"])
	{
		alert(ringNo + "环尚未施工！");
		return;
	}
	
	var ary = progList[svgID]["unreportedRings"];
	
	if(ary.contains(ringNo))
	{
		alert(ringNo + "环信息尚未入库！");
		return;
	}
	
		var url = "http://" + HOST_ADDR + "/cjsabms/common/external-ring.action?projectNo=1&sectionNo=" + sectionNo + "&ringNo=" + ringNo;
	 
	//var desc = "你点击了：" + line.ringNo + "环";
	
	window.open(url);
	
}

function _ringMouseDown(event)
{

	
	var line = event.srcElement;
	
	var ringNo;
	if(ringNo = prompt("请输入需要查看的环号：", line.ringNo))
	{
		if(!check_ring_no(ringNo))
		{
			alert("您输入的环号不正确");
			return;
		}
		
		show_detail_info(line.sectionNo, ringNo);
	}

}

function _setProgress(id, sectionNo, ringNo, lastRec, unreportedRings)
{
	var svg = getId(id);
	var width = parseInt(svg.style.width);
	var height = parseInt(svg.style.height);
	var totalRingNo = parseInt(progList[id]["ringNum"]);
	var direction = progList[id]["direction"];
	
	var dist = width / totalRingNo;
	var start = 0;
	if(direction == "r2l")
	{
		dist = -dist;
		start = width;
	}
	
	var g = svg.firstChild;
	while (g.hasChildNodes()) {
		g.removeChild(g.firstChild);
	}
	
	for(var i = 0; i < totalRingNo + 1; i ++)
	{
		var x1 = start + dist * i;
		var x2 = x1;
		var y1 = 0;
		var y2 = height;
		var styleStr = "";
		var status = "";
		if( i <= ringNo)
		{
			styleStr = "stroke:green;stroke-width:0.1";
			status = "normal";
		}
		else
		{
			styleStr = "stroke:gray;stroke-width:0.1";
			status = "unfinished";
		}
		
		if(unreportedRings.contains(i))
		{
			styleStr = "stroke:red;stroke-width:0.1";
			status = "unreported";
		}
		
		var line = document.createElementNS('http://www.w3.org/2000/svg','line');
		line.setAttribute("x1",x1);
		line.setAttribute("y1",y1);
		line.setAttribute("x2",x2);
		line.setAttribute("y2",y2);
		line.setAttribute("style",styleStr);
		line.ringNo = i;
		line.status = status;
		line.sectionNo = sectionNo;
		if( i == ringNo && lastRec)
			line.record = lastRec;
		line.onmouseover = _ringMouseIn;
		line.onmouseout = _ringMouseOut;
		line.onmousedown = _ringMouseDown;
		g.appendChild(line);
	}

}

function _initProgress()
{
	_drawProg(100,356,307,16,"progSvg0");
	progList["progSvg0"]["ringNum"] = 866;
	progList["progSvg0"]["direction"] = "r2l";
	progList["progSvg0"]["curRingNo"] = 0;
		
	_drawProg(100,394,307,16,"progSvg1");
	progList["progSvg1"]["ringNum"] = 859;
	progList["progSvg1"]["direction"] = "r2l";
	progList["progSvg1"]["curRingNo"] = 0;
	
	_drawProg(571,356,353,16,"progSvg2");
	progList["progSvg2"]["ringNum"] = 980;
	progList["progSvg2"]["direction"] = "l2r";
	progList["progSvg2"]["curRingNo"] = 0;
	
	_drawProg(571,394,353,16,"progSvg3");
	progList["progSvg3"]["ringNum"] = 1001;
	progList["progSvg3"]["direction"] = "l2r";
	progList["progSvg3"]["curRingNo"] = 0;
}


function _buildMap(imgName, image_seq)
{
	parent_id="mainDiv";
	element_id = "mapDiv";
	img_url = "images/" + image_seq + ".svg";
	
	//if an element with the same id exists, delete it first!
	var old_element = document.getElementById(element_id);
	if(old_element)
	{
		p = old_element.parentNode;
		p.removeChild(old_element);
	}
	
	parentDiv = getId(parent_id);
	
	var currentDiv = document.createElement("DIV");
	currentDiv.setAttribute("id", "mapDiv");
	
	var mapImg = document.createElement("img");
	mapImg.setAttribute("id", "mapImg");
	mapImg.setAttribute("src", img_url);
	//The following two magic lines must be put here!
	//If you comment it out, you will find a very annoying bug:
	//the second createElement call to create a svg img object will return with stale state and 
	//in this state you will not be able to change image scale for that img object;
	mapImg.style.width = "1024px";
	mapImg.style.height = "768px";
	mapImg.style.zIndex = "7";
	
	currentDiv.appendChild(mapImg);
	currentDiv.style.textAlign = "center";
	currentDiv.style.position = "absolute";
	currentDiv.style.zIndex = "8";
	currentDiv.style.title = imgName;
	currentDiv.style.border = "1px solid #eaeaea";
	currentDiv.style.cursor = "move";
	currentDiv.style.margin = "0px";
	currentDiv.style.padding = "0px";
	currentDiv.style.top = "0px";
	currentDiv.style.left = "0px";
	currentDiv.oncontextmenu = new Function("return false;");

	parentDiv.appendChild(currentDiv);
	
	
	if(image_seq == 1)
	{
		_initProgress();
	}
}

function _init()
{
	_addMinMap("1");
	_addMinMap("2");
	_addMinMap("3");
	
	//绘制当前地图
	_buildMap(curMap, curMap);
	
	//异步拉取所有读头数据，并在回调中异步拉取所有读头与地图的映射数据
	_fetchReaderStatusFlow();
	
}

function buildRead(lrmID, lrmName, lrmType, lrmX, lrmY, lrmState, lrmTime,
		lrmRemark, lrmRadius) {
	readList[readLen] = new Array();
	readList[readLen][0] = lrmID;
	readList[readLen][1] = lrmName;
	readList[readLen][2] = lrmType;
	readList[readLen][3] = lrmX;
	readList[readLen][4] = lrmY;
	readList[readLen][5] = lrmState;
	readList[readLen][6] = lrmTime;
	readList[readLen][7] = lrmRemark;
	readList[readLen][8] = lrmRadius;
	readLen = readLen + 1;
	drawRead(lrmID, lrmName, lrmX, lrmY, lrmState, lrmRadius);
};
function buildArea(areaID, areaName, areaType, areaX, areaY, readers) {
	areaList[areaLen] = new Array();
	areaList[areaLen][0] = areaID;
	areaList[areaLen][1] = areaName;
	areaList[areaLen][2] = areaType;
	areaList[areaLen][3] = areaX;
	areaList[areaLen][4] = areaY;
	areaList[areaLen][5] = readers;
	areaLen = areaLen + 1;
	drawArea(areaID, areaName, areaType, areaX, areaY);
};
function drawArea(areaID, areaName, areaType, areaX, areaY) {
	moveFlag = "area";
	var parentDiv = getId("mapDiv");
	var currentDiv = document.createElement("DIV");
	currentDiv.setAttribute("id", "area" + areaID);
	currentDiv.setAttribute ("title", "区域名称:" + areaName + "类型:" + areaType);
	currentDiv.style.background = "url(/SCMDB/images/area.gif) no-repeat";
	currentDiv.style.position = "absolute";
	currentDiv.style.zIndex = "200";
	currentDiv.style.border = "0px solid #000";
	currentDiv.style.cursor = "pointer";
	currentDiv.style.margin = "0px";
	currentDiv.style.height = "16px";
	currentDiv.style.width = "16px";
	currentDiv.style.padding = "0px 0px 0px 15px";
	currentDiv.style.left = areaX + "px";
	currentDiv.style.top = areaY + "px";
	currentDiv.oncontextmenu = new Function("return false;");
	
	var spanIn=document.createElement("span");
	spanIn.setAttribute("id", "inAreaSpan" + areaID);
	spanIn.style.border = "0px solid #000000";
	spanIn.style.lineHeight="20px";
	spanIn.style.color="red";
	spanIn.style.fontWeight="bold";
	spanIn.style.fontSize="18px";
	currentDiv.appendChild(spanIn);
	parentDiv.appendChild(currentDiv);
}
function drawRead(lrmID, lrmName, lrmX, lrmY, lrmState, lrmRadius) {
	moveFlag = "read";
	var parentDiv = getId("mapDiv");
	var currentDiv = document.createElement("DIV");
	currentDiv.setAttribute("id", "read" + lrmID);
	currentDiv.setAttribute ("title", "读头号:" + lrmID + ", 名称:" + lrmName);
	currentDiv.style.background = "url(/SCMDB/images/reader.gif) no-repeat";
	currentDiv.style.position = "absolute";
	currentDiv.style.border = "0px solid #000";
	currentDiv.style.cursor = "pointer";
	currentDiv.style.margin = "0px";
	currentDiv.style.height = "16px";
	currentDiv.style.width = "5px";
	currentDiv.style.padding = "0px 0px 0px 15px";
	currentDiv.style.left = lrmX + "px";
	currentDiv.style.top = lrmY + "px" ;
	currentDiv.style.zIndex = "200";
	currentDiv.oncontextmenu = new Function("return false;");
	
	var currentCanvas = document.createElement("CANVAS");
	currentCanvas.setAttribute("id", "readRadius" + lrmID);
	var radius = lrmRadius*0.4;
	currentCanvas.style.position = "absolute";
	currentCanvas.style.left = lrmX - radius + "px";
	currentCanvas.style.top = lrmY - radius + "px";
	currentCanvas.style.zIndex = "190";
	currentCanvas.width = radius * 2;
	currentCanvas.height = radius * 2;
	var context = currentCanvas.getContext('2d');
	context.globalAlpha = 0.5;
	var centerX = currentCanvas.width / 2;
	var centerY = currentCanvas.height / 2;
	context.beginPath();
	context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
	context.fillStyle = 'yellow';
	context.fill();
	//context.lineWidth = 5;
	context.strokeStyle = '#003300';
	context.stroke();
	currentCanvas.style.display="none";
	currentCanvas.oncontextmenu = new Function("return false;");
	parentDiv.appendChild(currentCanvas);

	var spanIn=document.createElement("span");
	spanIn.setAttribute("id", "inSpan" + lrmID);
	spanIn.style.border = "0px solid #000000";
	spanIn.style.lineHeight="15px";
	spanIn.style.color="green";
	spanIn.style.fontWeight="bold";
	spanIn.style.fontSize="12px";
	spanIn.style.paddingLeft="4px";
	currentDiv.appendChild(spanIn);
	
	var spanOut=document.createElement("span");
	spanOut.setAttribute("id", "outSpan" + lrmID);
	spanOut.style.border = "0px solid #000000";
	spanOut.style.lineHeight="30px";
	spanOut.style.color="green";
	spanOut.style.fontWeight="bold";
	spanOut.style.fontSize="16px";
	spanOut.style.paddingLeft="2px";
	currentDiv.appendChild(spanOut);
	
	
	currentDiv.style.display="none";
	parentDiv.appendChild(currentDiv);
}

function _addMinMap(image_seq)
{	
	img_url = "images/" + image_seq + ".svg";

	var minMapImg = document.createElement("img");
	minMapImg.setAttribute("id", "minMap_" + image_seq);
	minMapImg.setAttribute("src", img_url);
	minMapImg.style.width ="220px";
	minMapImg.style.height ="150px";
	minMapImg.style.border="1px solid #000000";
	minMapImg.onclick =function(event){
		curMap = image_seq;
		_drawPerMapReader();
		getId("hideAllReadersChk").checked = false;
		getMouseOffset(getId('minMap_' + image_seq),event,parseInt(minMapImg.style.width),parseInt(minMapImg.style.height));
	}; 
	
	getId('detailDiv').appendChild(minMapImg);
}

function initMinMap(id,width,height){
}

function _setAllProg()
{
	var all_id = ["progSvg0", "progSvg1", "progSvg2", "progSvg3"];
	
	for(var i = 0; i < all_id.length; i ++)
	{
		_setProgress(all_id[i], _svgID2SectionNo(all_id[i]), progList[all_id[i]]["curRingNo"], progList[all_id[i]]["lastRingRecord"], progList[all_id[i]]["unreportedRings"]);
	}
	
}

